<?php

namespace app\index\controller;

use app\api\model\Member;
use think\facade\View;

class Index
{

    public function __construct()
    {
        $memberId = session('member_id');
        if (!empty($memberId)) redirection('/index/member/index/');
    }

    public function index()
    {
        View::assign('url', 'https://www.baidu.com/');
        return View::fetch();
    }

    public function login()
    {
        //第一步：接收必要的参数，并完成参数的校验
        $mobile = input('post.mobile');
        $password = input('post.password');
        $captcha = input('post.captcha');
        if (empty($mobile)) output_error('手机号不能为空');
        if (empty($password)) output_error('密码不能为空');
        if (empty($captcha)) output_error('验证码不能为空');
        if (!captcha_check($captcha)) output_error('验证码错误');
        //第二步：使用账号与密码去数据库匹配
        $condition = array();
        $condition[] = ['member_mobile', '=', $mobile];
        $condition[] = ['member_password', '=', md5($password)];
        $member = Member::where($condition)->find();
        if (empty($member)) output_error('账号或密码错误');
        //第三步：匹配成功，生成TOKEN返回给客户端，匹配失败，提示账号或密码错误
        session('member_id', $member['member_id']);
        header("Content-Type: application/json; charset=UTF-8");
        $array = array();
        $array['code'] = 1;
        $array['msg'] = 'success';
        $array['data'] = '1';
        echo json_encode($array);
    }

}
